package cn.bossfriday.im.api.processor.user;

import cn.bossfriday.common.register.HttpApiRoute;
import cn.bossfriday.common.rpc.actor.ActorRef;
import cn.bossfriday.im.api.actor.ApiAckActor;
import cn.bossfriday.im.common.api.ApiResponseHelper;
import cn.bossfriday.im.common.api.BaseHttpProcessor;
import cn.bossfriday.im.common.entity.result.ResultCode;
import cn.bossfriday.im.common.message.api.user.GetTokenRequest;
import cn.bossfriday.im.common.message.rpc.user.GetTokenInput;
import cn.bossfriday.im.common.rpc.message.ApiMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import lombok.extern.slf4j.Slf4j;

import static cn.bossfriday.im.common.constant.ApiConstant.API_ROUTE_KEY_USER_GET_TOKEN;
import static cn.bossfriday.im.common.constant.ImConstant.ACTOR_USER_GET_TOKEN;

/**
 * GetTokenProcessor
 *
 * @author chenx
 */
@Slf4j
@HttpApiRoute(apiRouteKey = API_ROUTE_KEY_USER_GET_TOKEN)
public class GetTokenProcessor extends BaseHttpProcessor {

    @Override
    protected void doRequest(ChannelHandlerContext ctx, FullHttpRequest httpRequest, String apiVersion, long appId) {
        try {
            GetTokenRequest request = this.getRequestPayload(httpRequest, GetTokenRequest.class);
            GetTokenInput input = GetTokenInput.builder()
                    .userId(request.getUserId())
                    .userName(request.getUserName())
                    .deviceId(request.getDeviceId())
                    .build();
            ApiMessage apiMessage = this.getApiMessage(apiVersion,
                    appId,
                    ACTOR_USER_GET_TOKEN,
                    request.getUserId(),
                    request.getUserId(),
                    input);

            ActorRef sender = this.getSender(ApiAckActor.class, ctx);
            this.routeMessage(apiMessage, sender);
        } catch (Exception ex) {
            log.error("HttpProcessor.doRequest() error!", ex);
            ApiResponseHelper.sendApiResponse(ctx, ResultCode.SYSTEM_ERROR);
        }
    }
}